﻿using MoetutuServer.Helper;
using MoetutuServer.PostHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using WordPressSharp;
using WordPressSharp.Models;

namespace MoetutuServer.WebSite.PicServer.TagUpdate
{
    class TagUpdateHelper
    {

        /// <summary>
        ///  修改单个文章
        /// </summary>
        /// <param name="OriginTag"></param>
        /// <param name="ChineseTag"></param>
        /// <param name="singleLink"></param>
        public static void StartTagModifySingle(string OriginTag, string ChineseTag, string singleLink)
        {
            string PostId = TextHelper.ReplaceText(singleLink, "https://pic.moetutu.com/", "");
            if (!TextHelper.PureDigits(PostId))
                MessageHelper.CustomMessage(string.Format("【{0}】格式不正确！", PostId));
            try
            {
                using (WordPressClient client = WordPressPostHelper.GetClient(StaticValue.PostUser))
                {
                    Post GetPost = PostHelper.WordPressPostHelper.GetPost(PostId, client);
                    if (GetPost == null)
                        return;
                    Console.WriteLine("修改" + singleLink);
                    bool ModifyFlag = ModifyTagExistence(GetPost, OriginTag, ChineseTag);
                    if (ModifyFlag)
                    {
                        Console.WriteLine("开始创建标签");
                        GetPost.Terms = AddTag(GetPost, ChineseTag, client);
                        PostHelper.WordpressModify.ReEdit(GetPost, client);
                    }
                }
            } catch (Exception ex) {

                PrintLog.Log(ex);
            }
          
           
        }
        /// <summary>
        /// 批量修改模式
        /// </summary>
        /// <param name="keywordFilePath"></param>
        internal static void BatchModifyForRoma(string keywordFilePath)
        {
            List<string> ReadAllLine = FileHelper.ReadAllLine(keywordFilePath);
            if (ReadAllLine.Count <= 0)
                return;
            string RomaInfo = ReadAllLine[0];
            ReadAllLine.RemoveAt(0);
            FileHelper.WriteUTF8List(keywordFilePath, ReadAllLine);
            if(RomaInfo!="")
            WebSite.PicServer.TagUpdate.UpdateforRoma.InitSearchForOldTag(RomaInfo);

            BatchModifyForRoma(keywordFilePath);
        }

        /// <summary>
        /// 添加标签到post
        /// </summary>
        /// <param name="getPost"></param>
        /// <param name="chineseTag"></param>
        private static Term[] AddTag(Post getPost, string chineseTag, WordPressClient client)
        {
            List<Term> TempTerms = getPost.Terms.ToList<Term>();
            Term term = PostHelper.WordPressPostHelper.CreateTagHelper(client, chineseTag);
            if (term == null)
                return getPost.Terms;

            TempTerms.Add(term);
            return TempTerms.ToArray();
        }

        /// <summary>
        /// 获取要修改的标签是否存在，如果不存在返回true，代表你要添加这个标签
        /// </summary>
        /// <param name="GetPost"></param>
        /// <param name="OriginTag"></param>
        /// <param name="ChineseTag"></param>
        /// <returns></returns>
        private static bool ModifyTagExistence(Post GetPost, string OriginTag, string ChineseTag)
        {
            bool ChineseExistence = false;
            foreach (Term SingleTerm in GetPost.Terms)
            {
                if (String.Equals(SingleTerm.Name, OriginTag, StringComparison.CurrentCultureIgnoreCase))
                {
                    Console.WriteLine("英文标签查询到：{0}", SingleTerm.Name);
                    #region 扫描中文标签
                    foreach (Term TempTerm in GetPost.Terms)
                    {
                        if (String.Equals(TempTerm.Name, ChineseTag, StringComparison.CurrentCultureIgnoreCase))
                        {
                            Console.WriteLine("中文标签同样存在，不修改。");
                            return false;
                        }
                    }
                    #endregion
                    return true;


                }
            }

            return ChineseExistence;
        }

        /// <summary>
        /// 搜索列表
        /// </summary>
        /// <param name="OrignTag"></param>
        /// <returns></returns>
        public static List<string> SearchList(string OrignTag)
        {
            List<string> TempList = new List<string>();
            string Url = "https://pic.moetutu.com/?s=" + TextHelper.TranscodingToUtf8(OrignTag);
            Console.WriteLine(Url);
            TempList.AddRange(ScannerPage(Url));

            return TempList;
        }
        /// <summary>
        /// 递归查询下一页
        /// </summary>
        /// <param name="ScannerUrl"></param>
        /// <returns></returns>
        public static List<string> ScannerPage(string ScannerUrl)
        {
            List<string> TempList = new List<string>();
            String Shtml = WebHelper.HttpGet(ScannerUrl);
            //nav-previous
            String NextUrl = HtmlHelper.GetFirstValue(HtmlHelper.GetLinkVlaueList(Shtml, "//div[@class='nav-previous']/a"));
            Console.WriteLine("下一页" + NextUrl);
            TempList = HtmlHelper.GetLinkVlaueList(Shtml, "//a[@class='thumb-holder-link']");
            if (NextUrl != "")
                TempList.AddRange(ScannerPage(NextUrl));

            return TempList;
        }
    }
}
